package com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyAdapter.MyAdapters;
import com.diudiutechnology.www.yadiudiu.util.http.HttpClient;
import com.diudiutechnology.www.yadiudiu.util.http.JsonTools;
import com.diudiutechnology.www.yadiudiu.util.utils.Constant;
import com.diudiutechnology.www.yadiudiu.util.utils.CustomLayout;
import com.diudiutechnology.www.yadiudiu.util.utils.MyProgressDialog;
import com.diudiutechnology.www.yadiudiu.util.utils.PermissionsChecker;
import com.diudiutechnology.www.yadiudiu.util.utils.PictureUtil;
import com.diudiutechnology.www.yadiudiu.util.utils.SelectPhotoPop;
import com.diudiutechnology.www.yadiudiu.util.utils.Sundry;
import com.diudiutechnology.www.yadiudiu.util.utils.ToastUtils;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.LoginActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MerchantsTypeModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyApplication;
import com.diudiutechnology.www.yadiudiu.R;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Administrator on 2017/9/19.
 * 通用图片管理
 * 0、添加购车  1、添加买房 2、发布房源
 */

public class GeneralPictureEditorActivity extends Activity implements View.OnClickListener, Callback.CommonCallback<String> {
    @Bind(R.id.retur)
    LinearLayout retur;

    @Bind(R.id.imageView_layout)//店铺广告图
            RelativeLayout imageView_layout;
    @Bind(R.id.customLayout)
    CustomLayout customLayout;
    @Bind(R.id.ad_pager)
    ViewPager ad_pager;
    @Bind(R.id.ad_layer)
    LinearLayout ad_layer; // 圈圈 布局

    @Bind(R.id.button)
    Button button; // 完成


    Context context;
    private SelectPhotoPop selectPhotoPop;
    private View viewkre;
    private MyProgressDialog mDialog;
    String Judge_interface = "0";//判断哪个接口   0、获取店铺资料 1、上传图片 2、上传店铺资料 3、删除图片
    String posstr = "";//传过来的值  0、添加购车  1、添加买房
    String Judge_posstr = "";//传过来的值 判断  0、单张图片  1、多张图片
    String posted = "";//循环广告
    String conumg = "";
    int pos = 0;//删除id
//    private DisplayImageOptions options;
//    private ImageLoader imageLoader;
    List<String> pics = new ArrayList<>();//图片数组
    List<String> addpics = new ArrayList<>();//图片数组
    MyAdapters adapter;
    String merchanttype = "";//类型

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewkre = View.inflate(this, R.layout.activity_general_picture_editor, null);
        setContentView(viewkre);
        ButterKnife.bind(this);
        context = this;
        initView();
    }

    private void initView() {
        retur.setOnClickListener(this);
        imageView_layout.setOnClickListener(this);
        button.setOnClickListener(this);
        if (getIntent() != null) {
            posstr= getIntent().getStringExtra("pos");
            Judge_posstr= getIntent().getStringExtra("Judge_posstr");
            conumg = getIntent().getStringExtra("conumg");
        }
//        options = ImgUtils.imageOptions();
//        imageLoader = ImageLoader.getInstance();
//        imageLoader.init(ImageLoaderConfiguration.createDefault(context));


        adapter = new MyAdapters(context, pics,1);
        ad_pager.setAdapter(adapter);
        if (Judge_posstr.equals("0")){
            processupload(conumg);
        }else {
            if (!conumg.equals("")){
                String[] split = conumg.split("\\|");
                for (int i=0;i<split.length;i++){
                    pics.add(split[i]);
                }
                addpics = pics;
                getadvertising(pics.size());
                customLayout.setVisibility(View.VISIBLE);
            }
        }

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retur:
                finish();
                break;

            case R.id.imageView_layout://添加广告
                if (addpics.size() < 6) {
                    processadd("2");
                } else {
                    ToastUtils.show(context, getResources().getString(R.string.add_six_images));
                }
                break;

            /* 注释  相机*/
            case R.id.item_popupwindows_camera:
                selectPhotoPop.dismiss();
                GalleryFinal.openCamera(Constant.CAMERA, MyApplication.getInstance().initGalley(Constant.CAMERA, 1), mOnHanlderResultCallback);
                break;
            /* 注释  相册*/
            case R.id.item_popupwindows_Photo:
                selectPhotoPop.dismiss();
                GalleryFinal.openGallerySingle(Constant.GALLERYSINGLE, MyApplication.getInstance().initGalley(Constant.GALLERYSINGLE, 1), mOnHanlderResultCallback);
                break;
            /* 注释  取消*/
            case R.id.item_popupwindows_cancel:
                selectPhotoPop.dismiss();
                break;
            case R.id.button://保存
                if (addpics.size() > 0) {
                    for (int i = 0; i < addpics.size(); i++) {
                        if (posted.equals("")) {
                            posted = addpics.get(i);
                        } else {
                            posted = posted + "|" + addpics.get(i);
                        }
                    }
                }

                Intent intent=new Intent();
                intent.putExtra("posted",posted);
                intent.putExtra("conumg", addpics.get(0));
                intent.putExtra("number",addpics.size()+"");
                if (posstr.equals("0")){
                    setResult(Constant.ADDCARIMG,intent);
                }else   if (posstr.equals("1")){
                    setResult(Constant.ADDHOUSE,intent);
                }else   if (posstr.equals("2")){
                    setResult(Constant.ADDRENTAL,intent);
                }
                finish();
                break;
        }
    }


    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            Bitmap bitmap = PictureUtil.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), Constant.WIDE, Constant.WIDE);
            String conimg = PictureUtil.saveBitmapFile(bitmap, String.valueOf(0));
            processupload(conimg);
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    //轮播广告
    public void getadvertising(final int size) {
        adapter.addImet(pics);
        ad_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                Sundry.refreshPoint(ad_layer, position % size, 0);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        Sundry.initPointsLayout(ad_layer, context, size, 0);
    }

    //删除轮播图
    public void processdeleting(int pos, String pic) {
//        this.pos = pos;
//        delfile(pic);
        pics.remove(pos);
        addpics = pics;
        if (pics.size() > 0) {
            getadvertising(pics.size());
        } else {
        finish();
        }
    }

    //调用相机
    private void processadd(String pos) {
        if (!PermissionsChecker.getPermissionsChecker(this, "0", 0)) {
            if (!PermissionsChecker.getPermissionsChecker(this, "0", 2)) {
                showSelectPicPop();
            } else {
                ToastUtils.show(context, "请检查是否打开储存权限");
            }
        } else {
            ToastUtils.show(context, "请检查是否打开相机权限");
        }
    }

    //相册
    private void showSelectPicPop() {
        selectPhotoPop = new SelectPhotoPop(this, this);
        selectPhotoPop.showAtLocation(viewkre, Gravity.BOTTOM, 0, 0);
    }


    //上传图片
    private void processupload(String upload) {
        if (Sundry.isOpenNetwork(context)) {
            Judge_interface = "0";
            mDialog = new MyProgressDialog(context);
            HttpClient.upload(upload, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }


    //删除图片
    private void delfile(String upload) {
        if (Sundry.isOpenNetwork(context)) {
            Judge_interface = "1";
            mDialog = new MyProgressDialog(context);
            HttpClient.delfile(upload, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    @Override
    public void onSuccess(String result) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        System.out.println("stringmd5result" + result);
        List<MerchantsTypeModel> getnote = JsonTools.getmerchanttype(result);
        if (getnote != null || getnote.size() > 0) {
            String error = getnote.get(0).getError();
            String mssage = getnote.get(0).getMssage();
            if (error.equals("200")) {
                String content = getnote.get(0).getResult();
                if (Judge_interface.equals("0")) {//图片
                    pics.add(pics.size(), content);
                    addpics = pics;
                    getadvertising(pics.size());
                    customLayout.setVisibility(View.VISIBLE);
                } else if (Judge_interface.equals("1")) {// 删除图片
                    pics.remove(pos);
                    addpics = pics;
                    if (pics.size() > 0) {
                        getadvertising(pics.size());
                    } else {
                        customLayout.setVisibility(View.GONE);
                        imageView_layout.setVisibility(View.GONE);
                    }
                }
            } else if (error.equals("105")) {
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                ToastUtils.show(context, mssage);
            } else {
                ToastUtils.show(context, mssage);
            }
        }
    }


    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onCancelled(Callback.CancelledException cex) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onFinished() {

    }
}



